package com.javacode2018.demo5;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

@Component
public class UserService {
    @Autowired
    protected UserDao userDao;

    @Autowired
    private UserService userService;

    @Transactional(propagation = Propagation.REQUIRED)
    public void insert() {
        this.userDao.insert("tom1");
        this.userDao.insert("tom1");
        this.userService.insert1();
        System.out.println("哈哈");
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void insert1() {
        this.userDao.insert("tom2");
        this.userDao.insert("tom2");
    }

    @Transactional(readOnly = true, propagation = Propagation.REQUIRED)
    public List<User> list() {
        BeanPropertyRowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
        List<User> result = this.userDao.jdbcTemplate.query("select name from t_user", rowMapper);
        return result;
    }

    public String name(int id) {
        List<String> list = this.userDao.jdbcTemplate.queryForList("select name from t_user where id = ?", new Object[]{id}, String.class);
        String s= this.userDao.jdbcTemplate.queryForObject("select name from t_user where id = ?", new Object[]{id}, String.class);
        return CollectionUtils.isEmpty(list) ? null : list.get(1);
    }
}
